//导入Vue
import Vue from 'vue'
//导入VueRouter
import VueRouter from 'vue-router'
import routes from '@/router/routes'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'
//设置VueRouter到Vue中
Vue.use(VueRouter)

//解决编程式路由往同一地址跳转时会报错的情况
const originalPush = VueRouter.prototype.push;
const originalReplace = VueRouter.prototype.replace;
//push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject)
        return originalPush.call(this, location, onResolve, onReject);
    return originalPush.call(this, location).catch(err => err);
};
//replace
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
    if (onResolve || onReject)
        return originalReplace.call(this, location, onResolve, onReject);
    return originalReplace.call(this, location).catch(err => err);
};

const router = new VueRouter({
    mode: 'hash',
    routes
})
NProgress.configure({ easing: 'ease', speed: 500, showSpinner: false })
router.beforeEach(async (to, from, next) => {
    NProgress.start()
    next()
    let whiteList = ['/login', '/register']
    //获取token
    const token = localStorage.getItem('token')
    //判断token是否存在
    if (token) {
        try {
            await Vue.prototype.$api.users.getUserInfoApi()
            await store.dispatch("menus/getHomeChildRoutesAsync")
            const childHomeRoute=store.state.menus.homeChildRoutes.map(item=>{
                let routeObj=null
                if(item.meta){
                  routeObj={
                     path:item.path,
                     component:()=>import(`@/views/${item.component}.vue`),
                     meta:{
                         breadcrumbList:item.meta.split(",")
                     }
                    }
                }else{
                 routeObj={
                     path:item.path,
                     component:()=>import(`@/views/${item.component}.vue`)
                    }
                }
                return routeObj
             })
             childHomeRoute.forEach(item=>router.addRoute('home',item))
            router.addRoute({path:'*',redirect:'/404'})

        } catch (error) {
            console.log('error',error);
            Vue.prototype.$message.warning('token失效,请重新登录')
            localStorage.removeItem('token')
            next('/login')
        }
       
    } else {
        if (whiteList.includes(to.path)) {
            next()
        } else {
            next("/login")
        }
    }
  
})
router.afterEach(() => {
    NProgress.done()
})
export default router